  package com.e2e.haiti.infrastructure.surveyor;

import java.io.File;

import com.actionbarsherlock.app.SherlockFragment;
import com.e2e.haiti.infrastructure.surveyor.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class FragmentExtraPhotos  extends SherlockFragment {
	
    private Utils utilsHelper = null;
    private Cursor structureCursor = null;
    private int structureID;
    private Context mContext =  null;
    private static int CAPTURE_IMAGE = -1;
    private View mView = null;

    
    private static final int CAPTURE_IMAGE_EXTRA_1 = 0;
    private static final int CAPTURE_IMAGE_EXTRA_2 = 1;
    private static final int CAPTURE_IMAGE_EXTRA_3 = 2;
    private static final int CAPTURE_IMAGE_EXTRA_4 = 3;
    private static final int CAPTURE_IMAGE_EXTRA_5 = 4;
    
    private EditText EditText_Extra_Picture1  = null;
	private EditText EditText_Extra_Picture2  = null;    
	private EditText EditText_Extra_Picture3  = null;
	private EditText EditText_Extra_Picture4  = null;    
	private EditText EditText_Extra_Picture5  = null; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                
        utilsHelper = new Utils(getActivity().getApplicationContext());              
                 
    } // end of the onCreate method
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	
    	// Sets the cursor
        setStructureCursor(); 
    	
    	View mView = inflater.inflate(R.layout.extra_photos_layout, container, false);
   		setupPhotoButtons(mView);
    	manageFormFields(mView);

   		return mView;
    }
    
    private void setStructureCursor(){
        utilsHelper.openDatabase(); 
   	   // Get structure ID
          structureID = getActivity().getIntent().getIntExtra("structureID", -1); //Get structureID otherwise -1      
          structureCursor = utilsHelper.getStructureCursor(structureID); 
          utilsHelper.closeDatabase(); 
      }


    private void setupPhotoButtons(View v){
    	
    	// Extra Photo Button 1 =================================================================================
    	ImageButton btnPhoto1 = (ImageButton) v.findViewById(R.id.Extra_btn_Picture1);
    	
        if (photoAlreadyTaken(CAPTURE_IMAGE_EXTRA_1)){
        	btnPhoto1.setImageResource(R.drawable.check);
        } 
    	
        btnPhoto1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_EXTRA_1);
           
            }
        }); // End of Extra Photo Button 1 click listener   
    	
    	// Extra Photo Button 2 =================================================================================
        ImageButton btnPhoto2 = (ImageButton) v.findViewById(R.id.Extra_btn_Picture2);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_EXTRA_2)){
        	btnPhoto2.setImageResource(R.drawable.check);
        } 
        
        btnPhoto2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_EXTRA_2);
                   	
           
            }
        }); // End of Extra Photo Button 2 click listener   
        
    	//  Extra Photo Button 3 =================================================================================
        ImageButton btnPhoto3 = (ImageButton) v.findViewById(R.id.Extra_btn_Picture3);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_EXTRA_3)){
        	btnPhoto3.setImageResource(R.drawable.check);
        } 
        
        btnPhoto3.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                   	takePhoto(CAPTURE_IMAGE_EXTRA_3);
          
            }
        }); // End of Extra Photo Button 3 click listener   
        
    	// Extra Photo Button 4 =================================================================================
        ImageButton btnPhoto4 = (ImageButton) v.findViewById(R.id.Extra_btn_Picture4);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_EXTRA_4)){
        	btnPhoto4.setImageResource(R.drawable.check);
        } 

        btnPhoto4.setOnClickListener(new OnClickListener() {
        	
            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_EXTRA_4);           	
           
            }        
        }); // End of Extra Photo Button 4 click listener   
        
    	//  Extra Photo Button 5 =================================================================================
        ImageButton btnPhoto5 = (ImageButton) v.findViewById(R.id.Extra_btn_Picture5);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_EXTRA_5)){
        	btnPhoto5.setImageResource(R.drawable.check);
        } 
        
        btnPhoto5.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                   	takePhoto(CAPTURE_IMAGE_EXTRA_5);
          
            }
        }); // End of Extra Photo Button 5 click listener   
        // ========================================================================================================
    }  
    
    private boolean photoAlreadyTaken(int extra_photo){
    	
    	boolean exists = false;
    	String photo_value =  null;
    	
    	switch (extra_photo){
    	
    		case CAPTURE_IMAGE_EXTRA_1:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_1));
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_2:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_2));
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_3:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_3));
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_4:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_4));
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_5:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_5));
    			break;    			
    			
            default:
//            	Log.d(LAYOUT_INFLATER_SERVICE, "IMAGE EXISTS ERROR");
            	break;	
    			    	
    	}
    	
    	if (photo_value != null){
    		if (!photo_value.equals("")){
    			exists = true;
    		}
    	}

    	return  exists;
    }
    
    private void manageFormFields(View v){

    	// Declares the text input fields
    	EditText_Extra_Picture1 = (EditText) v.findViewById(R.id.Extra_editText_Picture1);
    	EditText_Extra_Picture2 = (EditText) v.findViewById(R.id.Extra_editText_Picture2);    
    	EditText_Extra_Picture3 = (EditText) v.findViewById(R.id.Extra_editText_Picture3);
    	EditText_Extra_Picture4 = (EditText) v.findViewById(R.id.Extra_editText_Picture4);    
    	EditText_Extra_Picture5 = (EditText) v.findViewById(R.id.Extra_editText_Picture5); 
	    
        // Checks if data already exists for Edit Text
        String picture1Note = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_1));
		String picture2Note = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_2));
		String picture3Note = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_3));
		String picture4Note = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_4));
		String picture5Note = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_EXTRA_5));
		
		// Sets the text of the input fields
		EditText_Extra_Picture1.setText(picture1Note);
		EditText_Extra_Picture2.setText(picture2Note);    
		EditText_Extra_Picture3.setText(picture3Note);
		EditText_Extra_Picture4.setText(picture4Note);    
		EditText_Extra_Picture5.setText(picture5Note); 
    }   
    
    private void takePhoto(int extra_photo){
	
    	// Determines which photo
    	CAPTURE_IMAGE = extra_photo;
    	
    	String photoPath = getPhotoPath(extra_photo); 
    	        
        File outFile = new File(photoPath); 	
    	Uri iImageOutputUri = Uri.fromFile( outFile );

    	// Start camera intent to capture image and store the file locally
    	// REQ: 3.4.4.R3 met
    	Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
    	intent.putExtra( MediaStore.EXTRA_OUTPUT, iImageOutputUri );

        utilsHelper.closeDatabase();
    	startActivityForResult(intent, CAPTURE_IMAGE);  	
    	}
    
    private String getPhotoPath(int photoSide){
    	    	
    	
		File file = Environment.getExternalStorageDirectory();
	    String structureName = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME));	 			
        String photo_directory = file.getAbsolutePath() + "/Haiti_Structure_Photos/" + structureName ;
        
        // Creates new directory if needed
    	File dir = new File(photo_directory);
        if (!dir.isDirectory())
            dir.mkdirs();
        
        String photoText = "";
    	
    	switch (photoSide){
    		
    		case CAPTURE_IMAGE_EXTRA_1:
    			photoText = "Extra1";
    			break;
    		case CAPTURE_IMAGE_EXTRA_2:
    			photoText = "Extra2";
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_3:
    			photoText = "Extra3";
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_4:
    			photoText = "Extra4";
    			break;
    			
    		case CAPTURE_IMAGE_EXTRA_5:
    			photoText = "Extra5";
    			break;    			
    			
            default:
//            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Image");
            	break;		 		    		
    	}
    	
    	String photoPath = photo_directory + File.separator + structureName + "_" + photoText + ".jpg";
		
    	return photoPath;  		
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {  

	 	if (resultCode == getActivity().RESULT_OK) {
	 		
	        utilsHelper.openDatabase();
	        
   	//  Extra Photo Button 1 =================================================================================
	 		if (requestCode == CAPTURE_IMAGE_EXTRA_1){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_EXTRA_1);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 		        
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_1, photoPath},
	                        };
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 				ImageButton btnPhoto1 = (ImageButton) getView().findViewById(R.id.Extra_btn_Picture1);
	 				btnPhoto1.setImageResource(R.drawable.check);
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}

	 		}
	 		
  //  Extra Photo Button 2 =================================================================================
	 		if (requestCode == CAPTURE_IMAGE_EXTRA_2){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_EXTRA_2);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_2, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 						
	 		        ImageButton btnPhoto2 = (ImageButton) getView().findViewById(R.id.Extra_btn_Picture2);
	 		       btnPhoto2.setImageResource(R.drawable.check);
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}

	 		}
	 		
   	//  Extra Photo Button 3 =================================================================================
	 		if (requestCode == CAPTURE_IMAGE_EXTRA_3){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_EXTRA_3);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_3, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnPhoto3 = (ImageButton) getView().findViewById(R.id.Extra_btn_Picture3);
	 		        btnPhoto3.setImageResource(R.drawable.check);
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}
	 		
   	//  Extra Photo Button 4 =================================================================================
	 		if (requestCode == CAPTURE_IMAGE_EXTRA_4){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_EXTRA_4);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_4, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnPhoto4 = (ImageButton) getView().findViewById(R.id.Extra_btn_Picture4);
	 		        btnPhoto4.setImageResource(R.drawable.check);	 			 				
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}

	//  Extra Photo Button 5 =================================================================================
	 		if (requestCode == CAPTURE_IMAGE_EXTRA_5){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_EXTRA_5);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_EXTRA_5, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnPhoto5 = (ImageButton) getView().findViewById(R.id.Extra_btn_Picture5);
	 		        btnPhoto5.setImageResource(R.drawable.check);	 			 				
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}	 		

	//  End =================================================================================
	 		
	 		utilsHelper.closeDatabase();

	    } // IF  RESULT ==  OK
  	
    } // On Activity Result
    
} 